package cn.flying.cloud.auth.security.details;

import javax.annotation.Resource;

import java.util.regex.Pattern;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import cn.flying.cloud.base.common.bo.UserInfo;
import cn.flying.cloud.system.feign.UserInfoApiClient;


/**
 * 自定义动态加载用户信息数据服务
 *
 * @author: admin
 * @date: 2022年11月07日 20:57
 * @version: 1.0
 */
@Component
public class CustomUserDetailService implements UserDetailsService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 手机号正则
     */
    public static final String MOBILE_REGEX = "^1[3-9]\\d{9}$";
    /**
     * 邮箱正则
     */
    public static final String EMAIL_REGEX = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";


    @Resource
    private UserInfoApiClient userInfoApiClient;

    /**
     * 加载用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetail userDetail = findUserByUsername(username);

        // 在admin模块已经统一处理了用户的角色和权限这里不做处理，直接获取判断
        if (CollectionUtils.isEmpty(userDetail.getPerms())) {
            return userDetail;
        }

        //用户的角色
//        if (CollectionUtils.isEmpty(userDetail.getRoles())) {
//            return userDetail;
//        }
//
//        List<String> authorities = new ArrayList<>();
//        //处理角色，增加前缀“ROLE_”
//        List<String> roles = userDetail.getRoles().stream().map(roleId -> "ROLE_" + roleId).distinct().collect(Collectors.toList());
//        authorities.addAll(roles);
//
//        //用户所有的权限资源
//        if (CollectionUtils.isNotEmpty(userDetail.getPerms())) {
//            authorities.addAll(userDetail.getPerms());
//        }

        // 这里不在缓存用户相关信息，由管理服务模块查询的时候再缓存
        //将用户的角色、资源、权限保存到Redis缓存中
//        redisService.set(Constants.AUTH_PERMS + ":" + userDetail.getTenantId() + ":" + userDetail.getUserId(), Ft.JSON.serializer(authorities));

        //包装当前用户的权限到
        userDetail.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", userDetail.getPerms())));
        return userDetail;
    }

    public UserDetail findUserByUsername(String username) {
        UserInfo userAuthInfo;
        if (Pattern.compile(MOBILE_REGEX).matcher(username).matches()) {
            logger.info("这是一个手机号，当前根据手机号查询用户信息！");
            userAuthInfo = userInfoApiClient.getUserAuthInfo(username, "mobile");
        } else if (Pattern.compile(EMAIL_REGEX).matcher(username).matches()) {
            logger.info("这是一个邮箱，当前根据邮箱查询用户信息！");
            userAuthInfo = userInfoApiClient.getUserAuthInfo(username, "email");
        } else {
            logger.info("这是普通文本，当前根据用户名查询用户信息！");
            userAuthInfo = userInfoApiClient.getUserAuthInfo(username, "username");
        }

        if (userAuthInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        UserDetail userDetail = new UserDetail();
        BeanUtils.copyProperties(userAuthInfo, userDetail);
        return userDetail;
    }
}
